package com.jbwz.web.security.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.conditions.query.QueryChainWrapper;
import com.jbwz.web.common.base.BaseServiceImpl;
import com.jbwz.web.common.base.IBasePage;
import com.jbwz.web.common.exception.BusinessException;
import com.jbwz.web.common.res.ResponseCodeBase;
import com.jbwz.web.security.entity.Role;
import com.jbwz.web.security.entity.vo.RoleVO;
import com.jbwz.web.security.mapper.RoleMapper;
import com.jbwz.web.security.service.RoleService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.Objects;

/**
 * <p>
 * 角色 服务实现类
 * </p>
 *
 * @author yyh
 * @since 2021-08-23 22:44:43
 */
@Slf4j
@Service
public class RoleServiceImpl extends BaseServiceImpl<RoleMapper, Role> implements RoleService {

    @Override
    public IBasePage pageList(IBasePage page, RoleVO vo) {
        vo.setCompanyId(getCurrentCid());
        return baseMapper.pageList(page, vo);
    }

    @Override
    public void saveOrUpdateVO(RoleVO vo) {
        QueryWrapper<Role> queryWrapper = queryWithCid().eq("name", vo.getName());
        Role role = baseMapper.selectOne(queryWrapper);
        if (Objects.nonNull(role)) {
            if (Objects.isNull(vo.getId()) || !role.getId().equals(vo.getId())) {
                throw BusinessException.resMsg(ResponseCodeBase.dataExist.withMsg(vo.getName() + "-角色已存在"));
            }
        }
        saveOrUpdate(toEntity(vo));
    }

    private Role toEntity(RoleVO vo) {
        Role role = new Role();
        role.setCompanyId(getCurrentCid());
        role.setId(vo.getId());
        role.setName(vo.getName());
        role.setDescription(vo.getDescription());
        return role;
    }
}
